//
//  ZYOAuthViewController.swift
//  weibo-Swift
//
//  Created by Apple on 16/7/24.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD
                        //授权界面

class ZYOAuthViewController: UIViewController {

    override func loadView() {
        self.view = webView
        
//        设置webview的代理
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
//    webView.backgroundColor = UIColor.yellowColor()
        setupNavigationBar()
//        加载登录界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
//        显示加载
//    SVProgressHUD.setMinimumDismissTimeInterval(2)
//        SVProgressHUD.showWithStatus("正在加载...")
        
    }

//   设置导航栏
    private func setupNavigationBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    
        self.navigationItem.title = "登录"
    }

    @objc func autoFill(){
        
    print("填充")
    }
    
    @objc func close(){
     self.dismissViewControllerAnimated(true, completion: nil)
    
    }
    
//  MARK:-  懒加载
    
//    webview
    private lazy var webView:UIWebView = UIWebView()
}



extension ZYOAuthViewController:UIWebViewDelegate{
//    webview加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
//     每当webview要加载一个网页都会调用这个方法，询问我们是否真的要去加载，返回：false 就不加载，返回true就去加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       
        let urlString = request.URL!.absoluteString
        print("加载到的地址：\(urlString)")

        //        其他界面不需要拦截，只需要拦截授权回调地址
        if !urlString.hasPrefix(redirect_uri){
//          不是授权回调地址，放过，去加载
            return true
            
        }else{
           let query = request.URL!.query!
            let codeString = "code="
           
            if query.hasPrefix(codeString){
            
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("截取到的code = \(code)")
            
            }else{
               print("点击取消")
            }
            return false
        }
        
    }
    
}




























